export function Googletag(html) {
    const result = { ...html };
    let hasAdSlot = false;

    for (const key in result) {
        if (key.startsWith("ad") && result[key]) {
            const value = result[key].replace(/\s+/g, "");
            const id = getIDs(value);
            if (id) {
                result[key] = getEachslot(id, value, key);
                hasAdSlot = true;
            } else {
                result[key] = "";
            }
        }
    }

    let gptScript = "";
    if (hasAdSlot) {
        gptScript += `<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>`;
        if (result.htmlTest?.trim()) {
            gptScript += `\n${result.htmlTest.trim()}\n`;
        }
    }

    const interstitial = result.interstitial?.trim() || "";
    const anchor = result.anchor?.trim() || "";
    if (interstitial || anchor) {
        gptScript += buildInterAchor(interstitial, anchor);
    }

    result.htmlTest = gptScript;

    return result;
}

function getIDs(adSlot) {
    const regex = /'([^']+)'\).addService\(googletag\.pubads\(\)\);/;
    const matches = adSlot.match(regex);
    return matches ? matches[1] : null;
}

function getEachslot(id, value, key) {
    if (!id) return "";

    const isIndexZero = /^ad\d+_0$/.test(key);
    const dataAttr = isIndexZero ? ' data-ad-index="0"' : "";

    return `
    <div class="ad-container"${dataAttr}>
      <!--${id}-->
      <div class='gptslot' id='${id}'>
        <script>
          window.googletag = window.googletag || {cmd: []};
          googletag.cmd.push(function() {
            ${value}
            googletag.pubads().enableSingleRequest();
            googletag.enableServices();
            googletag.display('${id}');
          });
        </script>
      </div>
    </div>`;
}


function buildInterAchor(inter, anchor) {
    if (inter === '' && anchor === '') { return ''; }
    let script = ``;
    script = `\n<script>
        window.googletag = window.googletag || { cmd: [] };
        googletag.cmd.push(function () {`
    if (inter) {
        script += ` // Define interstitial ad slot
        var interstitialSlot = googletag.defineOutOfPageSlot('${inter}', googletag.enums.OutOfPageFormat.INTERSTITIAL);
        if (interstitialSlot) {
            interstitialSlot.addService(googletag.pubads())
            googletag.display(interstitialSlot);
        }`
    }
    if (anchor) {
        script += `  
        var anchorSlot = googletag.defineOutOfPageSlot('${anchor}', googletag.enums.OutOfPageFormat.BOTTOM_ANCHOR);
        if (anchorSlot) {
            anchorSlot.addService(googletag.pubads())
            googletag.display(anchorSlot);
        }`;
    }
    script += `});
      </script>`;

    return script;

}


Googletag.exampleForm = {
    host: 'www.google.com',
    dirpath: 'example',
    html: {
        htmlTest: ``,
        hd_index: ``,
        hd_details: ``,
        hd_category: ``,
        hd_play: ``,
        ad0_0: `googletag.defineSlot('/000000/www.sitename/www.sitename_hometop1', [300, 250], 'div-gpt-ad-23296203343').addService(googletag.pubads());`,
        ad0_1: `googletag.defineSlot('/000000/www.sitename/www.sitename_homemiddle2', [300, 250], 'div-gpt-ad-23295593061').addService(googletag.pubads());`,
        ad0_2: `googletag.defineSlot('/000000/www.sitename/www.sitename_homebottom3', [300, 250], 'div-gpt-ad-23295593064').addService(googletag.pubads());`,
        ad0_3: `googletag.defineSlot('/000000/www.sitename/www.sitename_homebottom3-1', [300, 250], 'div-gpt-ad-23295593067').addService(googletag.pubads());`,
        ad0_4: `googletag.defineSlot('/000000/www.sitename/www.sitename_homebottom3-2', [300, 250], 'div-gpt-ad-23295593070').addService(googletag.pubads());`,
        ad1_0: `googletag.defineSlot('/000000/www.sitename/www.sitename_detailtop4', [300, 250], 'div-gpt-ad-23295591540').addService(googletag.pubads());`,
        ad1_1: `googletag.defineSlot('/000000/www.sitename/www.sitename_detailmiddle5', [300, 250], 'div-gpt-ad-23295593073').addService(googletag.pubads());`,
        ad1_2: `googletag.defineSlot('/000000/www.sitename/www.sitename_detailbottom6', [300, 250], 'div-gpt-ad-23295593076').addService(googletag.pubads());`,
        interstitial: `/000000/www.sitename/www.sitename_Interstitial7`,
        anchor: `/000000/www.sitename/www.sitename_Anchor8`,
    }
}

export function parseGptCode(rawInputString) {
    let inputString = rawInputString.split('\n').filter(line => line.length > 0).join(' ');
    const lines = (inputString.match(/[^;]+;/g) || []).filter(line => /define(?:OutOfPageSlot|Slot)\(/i.test(line));

    let commands = [];
    let paths = [];
    const slotRegex = /googletag\.define(?:OutOfPageSlot|Slot)\(([^)]+)\)/i;

    const obj = {
        type: 'googletag',
        items: {},
    };

    lines.forEach(line => {
        const match = line.match(slotRegex);
        if (match) {
            const Path_Match0 = match[0];
            const lowerPath = Path_Match0.toLowerCase();
            if (Path_Match0.includes('defineOutOfPageSlot')
                || lowerPath.includes('interstitial') || lowerPath.includes('anchor')
                || lowerPath.includes('-it7') || lowerPath.includes('-bn8')) {
                const pathMatch = Path_Match0.match(/'([^']+)'/);
                if (pathMatch && pathMatch[1]) {
                    const path = pathMatch[1];
                    if (!paths.includes(path)) {
                        paths.push(path);
                    }
                }
            } else {
                commands.push(`${Path_Match0}.addService(googletag.pubads());`);
            }
        }
    });

    getInterAnchorKey(obj.items, paths)

    // const magictagRegex = /<script[^>]*?src=["'][^"']*magictag[^"']*["'][^>]*?>[\s\S]*?<\/script>/gi;
    // const magictagScripts = [];
    // let match;
    // while ((match = magictagRegex.exec(rawInputString)) !== null) {
    //     magictagScripts.push(match[0].trim());
    // }

    commands = sortCommands(commands);
    assignAdKeys(obj.items, commands)
    return obj;
}

function getInterAnchorKey(items, paths) {
    let fallback = [];
    for (let i = 0; i < paths.length; i++) {
        const path = paths[i];
        const lower = path.toLowerCase();

        if (lower.includes(('interstitial') || lower.includes('-it')) && !items.interstitial) {
            items.interstitial = path;
        } else if ((lower.includes('anchor') || lower.includes('-bn')) && !items.anchor) {
            items.anchor = path;
        } else {
            fallback.push(path);
        }
    }

    if (!items.interstitial && fallback[0]) {
        items.interstitial = fallback[0];
    }
    if (!items.anchor && fallback[1]) {
        items.anchor = fallback[1];
    }
}

function assignAdKeys(items, commands) {
    let indexMap = { ad0: 0, ad1: 0, ad2: 0 };
    let uncategorized = [];

    commands.forEach(cmd => {
        const lower = cmd.toLowerCase();
        if (lower.includes('_hom') || lower.includes('-h')) {
            const key = `ad0_${indexMap.ad0++}`;
            items[key] = cmd;
        } else if (lower.includes('_det') || lower.includes('-d')) {
            const key = `ad1_${indexMap.ad1++}`;
            items[key] = cmd;
        } else if (lower.includes('_cate') || lower.includes('-c')) {
            const key = `ad2_${indexMap.ad2++}`;
            items[key] = cmd;
        } else {
            uncategorized.push(cmd);

        }
    });

    uncategorized.forEach((cmd, i) => {
        if (i < 4) {
            const key = `ad0_${indexMap.ad0++}`;
            items[key] = cmd;
        } else {
            const which = (i % 2 === 0) ? 'ad1' : 'ad2';
            const key = `${which}_${indexMap[which]++}`;
            items[key] = cmd;
        }
    });
}

function sortCommands(commands) {
    function getWeight(cmd) {
        const lower = cmd.toLowerCase();
        if (lower.includes('hom') || /\/[^\/]+_h[mtb]/.test(lower)) {
            if (lower.includes('_ht') || lower.includes('-ht') || lower.includes('hometop')) return 1;
            if (lower.includes('_hm') || lower.includes('-hm') || lower.includes('homemiddle')) return 2;
            if (lower.includes('_hb') || lower.includes('-hb') || lower.includes('homebottom')) return 3;
            return 9;
        }
        if (lower.includes('det') || /\/[^\/]+_d[mtb]/.test(lower)) {
            if (lower.includes('_dt') || lower.includes('-dt') || lower.includes('detailtop')) return 4;
            if (lower.includes('_dm') || lower.includes('-dm') || lower.includes('detailmiddle')) return 5;
            if (lower.includes('_db') || lower.includes('-db') || lower.includes('detailbottom')) return 6;
            return 10;
        }
        return 100;
    }
    return commands.sort((a, b) => getWeight(a) - getWeight(b));
}